package com.voltmao.service.application.doc;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.voltmao.persistent.mapper.DocDbMapper;
import com.voltmao.persistent.model.DocDb;
import com.voltmao.webpro.frame.dto.DataPage;
import com.voltmao.webpro.utils.ParamsUtil;
import com.voltmao.webpro.utils.PropertiesUtils;
import com.voltmao.webpro.utils.StringUtils;

import java.util.Date;
import java.util.Map;

/**
 * 文档管理服务层
 */
@Service
public class DocDbServiceImpl {
    @Autowired
    DocDbMapper docDbMapper;

    /**
     * 新增或更新文档
     * @param params
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public int insertOrUpdate(Map<String, Object> params) throws RuntimeException{

        //检查参数完整性
        String [] flag = {"flag"};
        ParamsUtil.checkNotNull(params,flag);
        String tmpFlag = params.get("flag").toString();
        //新增
        if(tmpFlag.equals("INSERT")){
            String[] checkParams = {"name","fileUrl","forCorpEmployesUser","forDocType"};
            ParamsUtil.checkNotNull(params,checkParams);
        }
        //更新
        if(tmpFlag.equals("UPDATE")){
            String[] checkParams = {"dataId"};
            ParamsUtil.checkNotNull(params,checkParams);
        }
        //删除
        if(tmpFlag.equals("DELETE")){
            String[] checkParams = {"dataId","isDel"};
            ParamsUtil.checkNotNull(params,checkParams);
        }

        DocDb docDb = (DocDb)PropertiesUtils.mapToObject(params,DocDb.class);
        if(StringUtils.isEmpty(docDb.getDataId())){
            docDb.setDataId(StringUtils.uuid36());
            docDb.setCreateDate(new Date());
            String [] tmp = docDb.getFileUrl().split("\\.");
            String fileType = tmp[1];
            docDb.setFileType(fileType);
            docDb.setIsDel(0);
            return docDbMapper.insert(docDb);
        }else{
            docDb.setUpdateDate(new Date());
            return docDbMapper.updateByPrimaryKeySelective(docDb);
        }
    }

    /**
     * 获取文档列表
     * @param params
     * @return
     */
    public DataPage getDocs(Map<String, Object> params){
        DataPage dataPage = new DataPage();
        int pageIdx = StringUtils.parseInt(params.get("pageNumber") + "", 1);
        int pageSize = StringUtils.parseInt(params.get("pageSize") + "", 20);
        dataPage.pageindex = pageIdx;
        dataPage.pagesize = pageSize;
        params.put("from",(pageIdx-1)*pageSize);
        params.put("pageSize",pageSize);

        dataPage.rows = docDbMapper.getDocs(params);
        dataPage.total = docDbMapper.countDocs(params);
        return  dataPage;
    }
}
